<?php

class RosterController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/columnMgt';
	public $sidebarMenu=array(
								array('label'=>'Roster Control', 'url'=>array('/roster/index')),
								array('label'=>'Shift Changes', 'url'=>array('/shiftChange/management')),
								array('label'=>'User Schedules', 'url'=>array('/schedule/index')),
								array('label'=>'Maintenance', 'url'=>array('/site/maintenance')),
								array('label'=>'Reporting', 'url'=>array('/site/reporting')),
							);

	
	protected function beforeAction($action) {
		if(!(Yii::app()->user->isGuest)) {
			$this->links =  Links::getTeamLinks(Yii::app()->user->team_id);
			
			if(empty($this->links)) {
				$this->links = array(array('label'=>'---','url'=>'#'));
				return true;
			} else
				return true;
		}
		else
			return true;
	}


	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}
	
	public function accessRules()
	{
		return array(

			array('allow', // allow admin user to perform the following actions
				'actions'=>array('index','indexTest','ajaxUserView','ajaxViewSchedule','ajaxScheduleChange','ajaxNextWeek','ajaxPreviousWeek'),
				'expression'=>'$user->can_create_edit_shifts == 1',
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function getWeekSchedulesGrid($team, $week, $year) {
		
		///<<<<<<----------------GET RELEVANT USERS  ------------------------------------------------------------->>>>
		
		// get list of enabled users 
		$users = User::model()->findAll(array('condition'=>'enabled = 1 and team = '.$team));
		
		///<<<<<<----------------DEFINE RELEVANT DATES------------------------------------------------------------->>>>
		$week_start = new DateTime();
		$week_start->setISODate($year,$week);
		
		//creating an array with dayOfWeek => date entries
		$daysArray = array();
		$daysArray['monday'] = $week_start->format('Y-m-d');
		$daysArray['tuesday'] = date('Y-m-d', strToTime('next Tuesday '.$week_start->format('Y-m-d')));
		$daysArray['wednesday'] = date('Y-m-d', strToTime('next Wednesday '.$week_start->format('Y-m-d')));
		$daysArray['thursday'] = date('Y-m-d',  strToTime('next Thursday '.$week_start->format('Y-m-d')));
		$daysArray['friday'] = date('Y-m-d',  strToTime('next Friday '.$week_start->format('Y-m-d')));
		$daysArray['saturday'] = date('Y-m-d',  strToTime('next Saturday '.$week_start->format('Y-m-d')));
		$daysArray['sunday'] = date('Y-m-d',  strToTime('next Sunday '.$week_start->format('Y-m-d')));
		
		
		///<<<<<<----------------DEFINE GLOBAL DATA CONTAINERS------------------------------------------------------------->>>>
		$rows = array();
				
		///<<<<<<----------------ITERATE THROUGH USERS------------------------------------------------------------->>>>
		foreach ($users as $user) {
			
			///<<<<<<----------------DEFINE USER DATA CONTAINER ARRAY------------------------------------------------------------->>>>
			$userRow = array();
			$userRow['iduser'] = $user->iduser;
			$userRow['batch'] = $user->batch;
			$userRow['username'] = $user->username;
			
			//Fills all days with the respective date and null value; days will be updated later if schedules for that day exist
			$userRow['monday'] = '---';
			$userRow['mondayDate'] = $daysArray['monday'];
			$userRow['tuesday'] = '---';
			$userRow['tuesdayDate'] = $daysArray['tuesday'];
			$userRow['wednesday'] = '---';
			$userRow['wednesdayDate'] = $daysArray['wednesday'];
			$userRow['thursday'] = '---';
			$userRow['thursdayDate'] = $daysArray['thursday'];
			$userRow['friday'] = '---';
			$userRow['fridayDate'] = $daysArray['friday'];
			$userRow['saturday'] = '---';
			$userRow['saturdayDate'] = $daysArray['saturday'];
			$userRow['sunday'] = '---';
			$userRow['sundayDate'] = $daysArray['sunday'];
				
			///<<<<<<----------------GET SCHEDULE PER DAY------------------------------------------------------------->>>>
			$userWeekSchedule = Schedule::getUserWeekSchedule($user->iduser,true,$week,$year);
			//print_r($userWeekSchedule);
			
			if($userWeekSchedule!=null) {
				
				foreach ($userWeekSchedule as $schedule) {
					///<<<<<<----------------ADD DAY ARRAY TO USER ARRAY------------------------------------------------------------->>>>
					///<<<<<<----------------ASSIGN PARAMETERS TO DAY ARRAY------------------------------------------------------------->>>>
					
					if($schedule->idweekday == Weekday::MONDAY) {
						/*echo "schedule id =".$schedule->idschedule."<br>";
						echo "  user id =".$schedule->iduser."<br>";
						echo "  teamid =".$schedule->team_id."<br>";
						echo "  week id =".$schedule->idweekday."<br>";
						echo "  shift id =".$schedule->idshift."<br>";
						echo " changed =".$schedule->wasChanged."<br>";
						echo "  qshift id =".$schedule->idqshift;exit;*/
						$userRow['monday'] = Shift::model()->findByPk($schedule->idshift)->name;
						if($schedule->isQshiftChange)
							$userRow['monday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['monday'] .= "**";
					} elseif ($schedule->idweekday == Weekday::TUESDAY) {
						$userRow['tuesday'] = Shift::model()->findByPk($schedule->idshift)->name;	
						if($schedule->isQshiftChange)
							$userRow['tuesday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['tuesday'] .= "**";		
					} elseif ($schedule->idweekday == Weekday::WEDNESDAY) {
						$userRow['wednesday'] = Shift::model()->findByPk($schedule->idshift)->name;
						if($schedule->isQshiftChange)
							$userRow['wednesday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['wednesday'] .= "**";			
					} elseif ($schedule->idweekday == Weekday::THURSDAY) {
						$userRow['thursday'] = Shift::model()->findByPk($schedule->idshift)->name;	
						if($schedule->isQshiftChange)
							$userRow['thursday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['thursday'] .= "**";		
					} elseif ($schedule->idweekday == Weekday::FRIDAY) {
						$userRow['friday'] = Shift::model()->findByPk($schedule->idshift)->name;
						if($schedule->isQshiftChange)
							$userRow['friday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['friday'] .= "**";		
					} elseif ($schedule->idweekday == Weekday::SATURDAY) {
						$userRow['saturday'] = Shift::model()->findByPk($schedule->idshift)->name;	
						if($schedule->isQshiftChange)
							$userRow['saturday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['saturday'] .= "**";		
					} elseif ($schedule->idweekday == Weekday::SUNDAY) {
						$userRow['sunday'] = Shift::model()->findByPk($schedule->idshift)->name;
						if($schedule->isQshiftChange)
							$userRow['sunday'] .= "*";
						elseif($schedule->wasChanged)
							$userRow['sunday'] .= "**";		
					}			
				}					
			}
			///<<<<<<----------------ADD USER ARRAY TO GLOBAL ARRAY------------------------------------------------------------->>>>
			
			//print_r($userRow);
			$rows[] = $userRow;
		} //ends forearch user
		
		///<<<<<<----------------FINAL GLOBAL ARRAY DETAILS------------------------------------------------------------->>>>
		
			
		///<<<<<<----------------RETURN FINAL GLOBAL PROVIDER/ARRAY ------------------------------------------------------------->>>>
		
		
			$dataProvider=new CArrayDataProvider($rows, array(
				'id'=>'dataProvider',
				'keyField'=>'iduser',
				
				'sort'=>array(
					'attributes'=>array(
						 'batch',
					),
				),
				'pagination'=>array(
					'pageSize'=>100,
				),
			));
			
			return $dataProvider;		
	}
	
	public function actionAjaxUserView($id)
	{
		$model = User::model()->findByPk($id);
		$this->renderPartial('_ajaxViewUser_form',array('model'=>$model),false,false);		
		
	}
		
	public function actionAjaxViewSchedule($id,$date)
	{
		//echo 'id = '.$id.', date = '.$date; exit;
		$model = Schedule::getUserScheduleForDate($id,$date);
		
		if ($model != null)
			$this->renderPartial('_ajaxViewSchedule',array('model'=>$model,'date'=>$date),false,true);
		else {
			$this->renderPartial('_ajaxViewSchedule',array('model'=>null,'userid'=>$id,'date'=>$date),false,true);
		}
	}
			
	public function actionAjaxScheduleChange($date)
	{
		$dateArray = explode('-',$date);
		$dateObject = new DateTime('NOW');
		$dateObject->setTimeZone(new DateTimeZone("America/Costa_Rica"));
		$dateObject->setDate($dateArray[0],$dateArray[1],$dateArray[2]);
		$week = $dateObject->format('W');
		$year = $dateObject->format('Y');
		
		$dateObject->setISODate($year,$week);	
		$monday = $dateObject->format('Y-m-d');		
		
		$this->renderPartial('_rosterGridView',
							 array(
								'currentWeek'=>$week,
								'year'=>$year,
								'monday'=>$monday,
							 ),
							 false,
							 true
							); 		
		
	}
		
	public function actionAjaxNextWeek()
	{
		$currentWeek= Yii::app()->session['currentWeek'];
				
		if($currentWeek!='52') {
			$nextWeek= $currentWeek+1;
			$year= Yii::app()->session['year'];
		} else {
			$nextWeek= '1';
			$year= Yii::app()->session['year']+1;	
		}
			
		$this->renderPartial('_rosterGridView',array('year'=>$year,
													 'currentWeek'=>$nextWeek,
													 false,
													 true
													)
							); 
		unset(Yii::app()->session['currentWeek']);
		unset(Yii::app()->session['year']);
		Yii::app()->session['currentWeek'] = $nextWeek;
		Yii::app()->session['year'] = $year;		
	}
			
	public function actionAjaxPreviousWeek()
	{
		$currentWeek= Yii::app()->session['currentWeek'];
				
		if($currentWeek!='1') {
			$previousWeek= $currentWeek-1;
			$year= Yii::app()->session['year'];
		} else {
			$previousWeek= '52';
			$year= Yii::app()->session['year']-1;	
		}
			
		$this->renderPartial('_rosterGridView',array('year'=>$year,
													 'currentWeek'=>$previousWeek,
													 false,
													 true
													)
							); 
		unset(Yii::app()->session['currentWeek']);
		unset(Yii::app()->session['year']);
		Yii::app()->session['currentWeek'] = $previousWeek;
		Yii::app()->session['year'] = $year;		
	}
	
	public function actionIndex($week=null,$year=null)
	{
		$dateObject = new DateTime('NOW');
		$dateObject->setTimeZone(new DateTimeZone("America/Costa_Rica"));			

		if($week==null) {
			$week = $dateObject->format('W');
			$year = $dateObject->format('Y');
		}
		
		$dateObject->setISODate($year,$week);	
		$monday = $dateObject->format('Y-m-d');					
		
		$this->render('index',
					  array(
							'currentWeek'=>$week,
							'year' => $year,
							'monday' => $monday,
					   )
					 );
	}
	
	

}
